import { defineStore } from "pinia";
// 1. 从新的 API 文件导入函数
import { addRecord, getDetail, getMessage, updateStatus, getFileContent } from "@/api/Matter";

// 2. 定义一个新的、独立的 store
//    ID 推荐使用 'matter' 或 'matterStore'，保持唯一性
export const useMatterStore = defineStore("matter", {
    // State: 存放这个模块相关的数据
    state: () => ({
        messages: [],       // 待办事项列表
        isLoading: false,   // 加载状态
        error: null,        // 错误信息
    }),

    // Actions: 业务逻辑和异步请求
    actions: {
        async fetchMessages(userId) {
            this.isLoading = true;
            this.error = null;
            try {
                const response = await getMessage(userId);
                this.messages = response.data; 
            } catch (err) {
                console.error("获取待办事项失败:", err);
                this.error = err;
            } finally {
                this.isLoading = false;
            }
        },

        async createRecord(recordData){
            const formData=new FormData();

            formData.append('messageId', recordData.messageId);
            formData.append('processorUserId', recordData.processorUserId);
            formData.append('id', recordData.id);
            formData.append('processInfo', recordData.processInfo);
            if (recordData.attachmentFile) {
                formData.append('attachment', recordData.attachmentFile);
            }
            try {
                const response = await addRecord(formData);
                console.log('记录创建成功:', response.data);
                return response; 
            } catch (error) {
                console.error('创建记录失败:', error);
                throw error;
            }
        },

        async upStatus(messageId,status){
            try{
                await updateStatus(messageId,status);
            }catch (error){
                console.error('状态更新失败', error);
                throw error;
            }
        },

        async detail(messageId){
            try{
                 const response=await getDetail(messageId);
                 return response.data;
            }catch (error){
                console.error('获取详情失败', error);
                throw error;
            }
        },

        async fetchFile(messageId) {
        try {
            const response = await getFileContent(messageId);
            return response.data; // response.data 现在是一个 Blob 对象
        } catch (error) {
            console.error('获取文件失败', error);
            throw error;
        }
    }

        
        // 添加其他 actions
    }
});